package com.hongmeng.teamwork.domain.impl;

import com.alibaba.fastjson.JSON;
import com.hongmeng.teamwork.config.FeishuProperties;
import com.hongmeng.teamwork.convert.TeamworkProjectGroupRelConvert;
import com.hongmeng.teamwork.domain.IGroupDomainService;
import com.hongmeng.teamwork.entity.dto.ProjectGroupRelDto;
import com.hongmeng.teamwork.entity.po.TeamworkProjectGroupRel;
import com.hongmeng.teamwork.service.ITeamworkProjectGroupRelService;
import com.hongmeng.teamwork.utils.FeishuUtil;
import com.lark.oapi.Client;
import com.lark.oapi.service.im.v1.enums.CreateChatMembersMemberIdTypeEnum;
import com.lark.oapi.service.im.v1.model.*;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.UUID;

@Log4j2
@Service
public class GroupDomainServiceImpl implements IGroupDomainService {

    @Resource
    private Client client;
    @Resource
    private FeishuProperties feishuProperties;
    @Resource
    private ITeamworkProjectGroupRelService projectGroupRelService;

    @Override
    public String createGroup(ProjectGroupRelDto projectGroupRelDto) {
        CreateChatResp resp;
        try {
            resp = client.im().chat()
                    .create(CreateChatReq.newBuilder()
                            .uuid(UUID.randomUUID().toString())
                            .createChatReqBody(CreateChatReqBody.newBuilder()
                                    .name(projectGroupRelDto.getName())
                                    .ownerId(projectGroupRelDto.getOpenId())
                                    .userIdList(new String[]{projectGroupRelDto.getOpenId()})
                                    .botIdList(new String[]{feishuProperties.getAppId()})
                                    .joinMessageVisibility("all_members")
                                    .build())
                            .build(),
                            FeishuUtil.getRequestOptionsByAccessToken(projectGroupRelDto.getAccessToken()));
        } catch (Exception e) {
            log.error("GroupServiceImpl.createGroup.error: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
        if (log.isInfoEnabled()) {
            log.info("GroupServiceImpl.createGroup.resp: {}", JSON.toJSONString(resp));
        }
        // 组装项目、群关联关系对象
        String chatId = resp.getData().getChatId();
        TeamworkProjectGroupRel projectGroupRel = TeamworkProjectGroupRelConvert.INSTANCE.convertDtoToEntity(projectGroupRelDto);
        projectGroupRel.setGroupId(chatId);
        projectGroupRel.setCreatedTime(LocalDateTime.now());
        projectGroupRelService.insert(projectGroupRel);
        return chatId;
    }

    @SneakyThrows
    @Override
    public String popUserIntoGroup(ProjectGroupRelDto projectGroupRelDto) {
        TeamworkProjectGroupRel projectGroupRel = projectGroupRelService.queryByProjectId(projectGroupRelDto.getProjectId());
        String groupId = projectGroupRel.getGroupId();
        // todo 此处可以加一层判断：如果用户在群中，无需再次邀请进群
        CreateChatMembersResp resp = client.im().chatMembers()
                .create(CreateChatMembersReq.newBuilder()
                                .chatId(groupId)
                                .memberIdType(CreateChatMembersMemberIdTypeEnum.OPEN_ID)
                                .createChatMembersReqBody(CreateChatMembersReqBody.newBuilder()
                                        .idList(projectGroupRelDto.getOpenIdList().toArray(new String[0]))
                                        .build())
                                .build(),
                        FeishuUtil.getRequestOptionsByAccessToken(projectGroupRelDto.getAccessToken()));
        return projectGroupRel.getGroupId();
    }
}
